"use strict";

import socket from "@ohos.net.socket";
import { EventEmitter } from "@ohos/node-polyfill";
var tls = socket.constructTLSSocketInstance()
import { parseURI } from "@xmpp/connection/src/main/connection/lib/util";

class Socket extends EventEmitter {
  constructor() {
    super();
    // process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
    this.listeners = Object.create(null);
    this.timeout = null;
  }

  async connect(service) {
    const { port, hostname } = parseURI(service);
    let options = {
      address: {
        address: hostname,
        port: port != "5223" ? 5223 : parseInt(port)
      },
      secureOptions: {},
      ALPNProtocols: ["spdy/1", "http/1.1"]
    };
      await tls.bind(options.address)
      tls.connect(options, (err) => {
        if (!err) {
          console.info('tlsSocket-----------------connect')
        } else {
          console.info('tlsSocket-----------------connect-err' + JSON.stringify(err))
        }
      })
    this._attachSocket(tls);
  }
  _attachSocket(socket) {
    this.socket = socket;
    const { listeners } = this;
    this.socket.on('close',()=>{
      this._detachSocket();
      this.emit("close");
    })
    this.socket.on('message',(data)=>{
      const uintArray = new Uint8Array(data.message)
      let str = ''
      for (let i = 0; i < uintArray.length; ++i) {
        str += String.fromCharCode(uintArray[i])
      }
      this.emit("data", str);
    })
    this.socket.on('error',(err)=>{
        this.emit("error", err);
    })
    this.socket.on('connect',()=>{
      if (this.socket.getProtocol() !== "TLSv1.2") {
        return this.emit("connect");
      }
      // Waiting before sending the stream header improves compatibility
      // with Openfire TLSv1.3 implementation. For more info, see:
      // https://github.com/xmppjs/xmpp.js/issues/889#issuecomment-902686879
      // https://github.com/xmppjs/xmpp.js/pull/912
      this.timeout = setTimeout(() => {
        this.emit("connect");
      }, 1);
    })
    // listeners.close = () => {
    //   // this._detachSocket(socket);
    //   this.emit("close");
    // };
    // listeners.data = (data) => {
    //   this.emit("data", data);
    // };
    // listeners.error = (err) => {
    //   this.emit("error", err);
    // };
    // listeners.secureConnect = () => {
    //   if (this.socket.getProtocol() !== "TLSv1.3") {
    //     return this.emit("connect");
    //   }
    //
    //   // Waiting before sending the stream header improves compatibility
    //   // with Openfire TLSv1.3 implementation. For more info, see:
    //   // https://github.com/xmppjs/xmpp.js/issues/889#issuecomment-902686879
    //   // https://github.com/xmppjs/xmpp.js/pull/912
    //   this.timeout = setTimeout(() => {
    //     this.emit("connect");
    //   }, 1);
    // };
    //
    // for (const [event, listener] of Object.entries(listeners)) {
    //   socket.on(event, listener);
    // }
  }

  _detachSocket() {
    clearTimeout(this.timeout);
    const { socket } = this;
    socket.off("message",(value)=>{
      console.info("tlsSocket--message--off")
    });
    socket.off("connect",()=>{
      console.info("tlsSocket--connect--off")

    });
    delete this.socket;
  }

 async  end() {
     await this.socket.close();
  }

  write(data, fn) {
    this.socket.send(data);
    fn()
  }
}

export default Socket;
